package com.itheima.service;

import com.itheima.exception.BusinessException;
import com.itheima.utils.AgreementUtil;

import java.io.*;
import java.net.Socket;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;

public class FileUpDownServiceImp implements Runnable, FileUpDownService {
    private final ResourceBundle bundle;
    private final File rootDir;
    private Socket socket;

    public FileUpDownServiceImp(Socket socket) {
        this.socket = socket;

        bundle = ResourceBundle.getBundle("yunpan");

        rootDir = new File(bundle.getString("rootDir"));
        if (rootDir.isFile()) {
            throw new BusinessException("根目录路径与已存在文件冲突");
        } else if (!rootDir.exists() && !rootDir.mkdirs()) {
            throw new BusinessException("根目录创建失败，请检查配置路径是否正确");
        }
    }

    @Override
    public void run() {
        try (Socket socket = this.socket;
             InputStream netIn = socket.getInputStream();
             OutputStream netOut = socket.getOutputStream();
        ) {
            final String agreement = AgreementUtil.receiveAgreement(netIn);
            String type = AgreementUtil.getType(agreement);
            switch (type) {
                case "SCAN":
                    scanDirectory(agreement, netIn, netOut);
                    break;
                case "DOWNLOAD":
                    downloadFile(agreement, netIn, netOut);
                    break;
                case "UPLOAD":
                    uploadFile(agreement, netIn, netOut);
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void scanDirectory(String agreement, InputStream netInput, OutputStream netOutput) throws IOException {
        String fileName = AgreementUtil.getFileName(agreement);
        String fileDir = fileName.replace("root", rootDir.toString());
        File dir = new File(fileDir);

        if (dir.isFile()) {
            String s = AgreementUtil.getAgreement("SCAN", null, "FAILED", "目录不存在，只能浏览当前子目录");
            AgreementUtil.sendAgreement(netOutput, s);
        } else {
            String s = AgreementUtil.getAgreement("SCAN", fileDir, "OK", null);
            AgreementUtil.sendAgreement(netOutput, s);

            OutputStreamWriter osw = new OutputStreamWriter(netOutput);
            File[] children = dir.listFiles();

            for (File child : children) {
                String fileType = child.isFile() ? "文件" : "目录";
                osw.write(fileType + " " + child.getName() + "\r\n");
            }

            osw.flush();
        }
    }

    @Override
    public void uploadFile(String agreement, InputStream netInput, OutputStream netOutput) throws IOException {

    }

    @Override
    public void downloadFile(String agreement, InputStream netInput, OutputStream netOutput) throws IOException {

    }
}
